import { Component, OnInit, AfterViewInit, OnDestroy, Output, EventEmitter } from '@angular/core';
import { AlarmService } from 'app/pages/traffic-management/traffic-alert/alarm.service';
import { NzMessageService, NzModalRef, NzModalService } from 'ng-zorro-antd';
import { MESSAGE_CHANNEL, SYSTEM_EVENT, SELECT_OPTIONS } from 'app/app.constants';
import { NotificationService, BullySubjectService, Bully } from 'app/shared/service';
import { filter, switchMap } from 'rxjs/operators';
import { Router, ActivatedRoute, Params, ParamMap } from '@angular/router';
import { PublicService } from 'app/public/public.service';
import * as moment from 'moment';
import { differenceInCalendarDays } from 'date-fns';
import { TranslateService } from '@ngx-translate/core';
import { SystemService } from 'app/service/system.service';
import { AuthService } from 'app/auth/auth.service';

@Component({
    selector: 'itmp-traffic-alert-page',
    templateUrl: './traffic-alert-page.component.html',
    styleUrls: ['./traffic-alert-page.component.css']
})
export class TrafficAlertPageComponent implements OnInit, AfterViewInit, OnDestroy {
    @Output() ignoreAlert = new EventEmitter();
    @Output() isIrSelected = new EventEmitter();
    pagination = {
        totalEle: 25,
        pageSize: 10,
        currentPage: 1,
        currentSize: 10
    };
    queryCondition = {
        detectionTime: null,
        alertID: null,
        zoneID: null,
        roadName: null,
        alertSource: null,
        ackBy: null,
        ackTime: null,
        ackValue: null
    };
    listOfData = [];
    renderHeader: any = [];
    editingItem = '';
    subscripion = [];
    toolbarList = [
        { className: 'icon-CCTV' },
        { className: 'icon-dingwei' },
        { className: 'icon-dayinfuyin-' },
        { className: 'icon-xiazai' }
    ];
    alertSourceList: any = [
        { label: 'All', value: null },
        { label: 'TSC', value: 'TSC' },
        { label: 'AID', value: 'AID' },
        { label: 'VMS', value: 'VMS' }
    ];
    description: any = [];
    dateRange = [];
    alertSwitch = true;
    dateRangeAck = [];
    queryStartTime = null;
    queryEndTime = null;
    queryAckStartTime = null;
    queryAckEndTime = null;
    selectItem = null;
    confirmModal: NzModalRef;
    showItem = '';
    queryData = null;
    loginUserName = ''; // 声明全局变量loginUserName,viet-316
    accessButton = {
        Ack: false,
        Ignore: false,
        export: false,
        GIS: false,
        PRINT: false,
        MONITOR: false
    };
    alertId = null;
    // zoneList = [];
    // zoneIdList = [];
    isForceVisible = false;
    // isForce = false;
    isShowVietName = false;
    isCreateTr = false;

    constructor(
        private alarmService: AlarmService,
        private message: NzMessageService,
        private bully: BullySubjectService,
        private router: Router,
        private modal: NzModalService,
        private route: ActivatedRoute,
        private pub: PublicService,
        private translate: TranslateService,
        private ss: SystemService,
        private authService: AuthService
    ) {}

    ngOnInit() {
        // this.getZoneIdListByUser();
        /*this.bully.zoneListBehavior.subscribe(res => {
            this.zoneList = res['selectZoneList'] ? res['selectZoneList'] : [];
        });*/
        this.getAllList();
        this.alertSwitch = JSON.parse(localStorage.getItem('alertSwitch'));
        this.loginUserName = localStorage.getItem('user_name'); // 获取LocalStorage里面的user_name,viet-316
        /*const subscripion = this.bully.getSubject().subscribe(res => {
            // alarm
            if (res['type'] === SYSTEM_EVENT.ALERT_EVENT) {
                /!* const features = {
					ackBy: null,
					ackTime: null,
					ackValue: null,
					alertCode: 'STOPPED_VEHICLE',
					alertDescription: 'Stopped',
					alertID: 'AID_DET_576632_STOPPED_VEHICLE' + Math.floor(Math.random() * (10000 - 1 + 1) + 1),
					alertSource: 'AID',
					clearTime: null,
					detectionTime: 1475976848000,
					direction: null,
					eqtId: 'DET_576632',
					laneId: '1',
					laneNo: 1,
					latitude: '30.667664',
					linkID: null,
					longitude: '104.072159',
					pic1Name: null,
					pic1Path: null,
					pic2Name: null,
					pic2Path: null,
					picX: null,
					picY: null,
					roadName: null,
					videoEndTime: null,
					videoStartTime: null,
					videoURL: null,
					zoneID: 5
				}; *!/
                const features = {
                    ...res['data'],
                    ackTime: res['data']['ackTime']['time'],
                    detectionTime: res['data']['detectionTime']['time']
                };
                this.getAlertBySocket(features);
            }
        });
        this.subscripion.push(subscripion);*/
        this.renderHeader = this.alarmService.renderHeader().slice(0, -3);
        // 从overall页面跳转后给Alert ID 赋值
        this.route.paramMap.pipe(switchMap((params: ParamMap) => params.getAll('id'))).subscribe(id => {
            if (id) {
                this.renderHeader.forEach(item => {
                    if (item.name === 'Alert ID') {
                        item.key = id;
                    }
                });
            }
            this.alertId = id;
        });
        this.getSelectionList();
        // this.description = this.alarmService.description();
        this.getAllList();
        this.getButtonAccess();
        if (localStorage.getItem('itmp_lang') === 'vi') {
            this.isShowVietName = true;
        } else {
            this.isShowVietName = false;
        }
    }

    /*getZoneIdListByUser() {
        const queryData = {
            condition: {
                userId: localStorage.getItem('user_id'),
                user_Name: localStorage.getItem('user_name'),
                user_Pwd: null,
                organization_Id: null,
                userRole_Id: null,
                createTime: {
                    startTime: null,
                    endTime: null
                },
                updateTime: {
                    startTime: null,
                    endTime: null
                }
            },
            pageNum: 1,
            pageSize: 999999
        };
        this.alarmService.getAllUser(queryData).subscribe(res => {
            const userZone = res.content.content[0].userZoneRel;
            userZone.forEach(zoneId => {
                this.zoneIdList.push(zoneId.vnqn_zone_id);
            });
        });
    }*/

    getSelectionList() {
        const res = this.pub.getSelectOptionsList(SELECT_OPTIONS.ALERT_TYPE);
        this.description = res.data;
        this.description.forEach(des => {
            if (localStorage.getItem('itmp_lang') === 'vi') {
                des.displayName = des.vietName;
            } else {
                des.displayName = des.name;
            }
        });
    }

    changeSwitch() {
        localStorage.setItem('alertSwitch', JSON.stringify(this.alertSwitch));
        const data: Bully = { type: SYSTEM_EVENT.ACK_ALERT, data: 'closeLayer' };
        this.bully.registerBroadcastSend(MESSAGE_CHANNEL.CCM_CHANNEL, data);
    }

    ngAfterViewInit(): void {
        /*const subscripion = this.bully
            .getBSubject()
            .pipe(filter(res => !!res))
            .subscribe(res => {
                // alarm
                if (res['type'] === SYSTEM_EVENT.ALERT_EVENT) {
                    /!* const features = {
                        ackBy: null,
                        ackTime: null,
                        ackValue: null,
                        alertCode: 'STOPPED_VEHICLE',
                        alertDescription: 'Stopped',
                        alertID: 'AID_DET_576632_STOPPED_VEHICLE' + Math.floor(Math.random() * (10000 - 1 + 1) + 1),
                        alertSource: 'AID',
                        clearTime: null,
                        detectionTime: 1475976848000,
                        direction: null,
                        eqtId: 'DET_576632',
                        laneId: '1',
                        laneNo: 1,
                        latitude: '30.667664',
                        linkID: null,
                        longitude: '104.072159',
                        pic1Name: null,
                        pic1Path: null,
                        pic2Name: null,
                        pic2Path: null,
                        picX: null,
                        picY: null,
                        roadName: null,
                        videoEndTime: null,
                        videoStartTime: null,
                        videoURL: null,
                        zoneID: 5
					}; *!/
                    const features = {
                        ...res['data'],
                        ackTime: res['data']['ackTime']['time'],
                        detectionTime: res['data']['detectionTime']['time']
                    };
                    setTimeout(() => this.getAlertBySocket(features));
                }
            });
        this.subscripion.push(subscripion);*/
    }

    // tslint:disable-next-line:use-life-cycle-interface
    ngOnDestroy() {
        this.bully.resetBSubject();
        this.subscripion.forEach(element => {
            if (element) {
                element.unsubscribe();
            }
        });
    }

    getButtonAccess() {
        this.accessButton = this.pub.getButtonAccess('13', this.accessButton);
    }

    // page change
    onPageChange(e) {
        this.pagination.currentPage = e;
        this.getAllList();
    }

    onSizeChange(e) {
        this.pagination.pageSize = e;
        this.pagination.currentPage = 1;
        this.getAllList();
    }

    getAllList() {
        const pageParam = {
            pageNo: this.pagination.currentPage,
            pageSize: this.pagination.pageSize
        };
        const dateParam = {
            startTime: this.queryStartTime,
            endTime: this.queryEndTime
        };
        const dateAckParam = {
            startTime: this.queryAckStartTime,
            endTime: this.queryAckEndTime
        };
        this.queryData = this.alarmService.formAlertData(this.renderHeader, dateParam, dateAckParam, pageParam, []);
        const qurey = this.alarmService.getTrafficAlert(this.queryData);
        qurey.subscribe(
            (res: any) => {
                this.listOfData = res.data.list;
                this.pagination.totalEle = res.data.totalCount;
                this.pagination.currentSize = res.data.numberOfElements;
            },
            (error: any) => {}
        );
    }

    showDetail(item): void {
        this.editingItem = item.alertID;
        this.selectItem = item;
    }

    initData() {
        // this.queryCondition = {
        //     detectionTime: null,
        //     alertID: null,
        //     zoneID: null,
        //     roadName: null,
        //     alertSource: null,
        //     ackBy: null,
        //     ackTime: null,
        //     ackValue: null
        // };
        this.renderHeader.forEach(item => {
            item.key = null;
        });
        this.queryStartTime = null;
        this.queryEndTime = null;
        this.queryAckStartTime = null;
        this.queryAckEndTime = null;
        this.selectItem = null;
        this.pagination = {
            totalEle: 25,
            pageSize: 10,
            currentPage: 1,
            currentSize: 10
        };
    }

    // 刷新
    refresh() {
        this.dateRange = [];
        this.dateRangeAck = [];
        this.initData();
        this.getAllList();
    }

    // 取消强制操作
    FourchHandleCancel() {
        this.isForceVisible = false;
    }

    // 确定强制操作
    ForceHandleOk() {
        // this.ignoreAlert.emit('ignore');
        const zoneIds = this.ss.userZoneList.filter(z => !z.isTemp).map(z => z.id);
        const editingData = {
            alertId: this.editingItem,
            ackValue: this.showItem === 'acknowledge',
            userName: this.loginUserName, // 使用loginUserName,viet-316,
            zoneId: zoneIds
        };
        const header = {
            zoneId: zoneIds.join(','),
            isFource: true
        };
        if (this.showItem === 'acknowledge') {
            this.alarmService.ackTrafficAlert(editingData, header).subscribe((res: any) => {
                if (res.msg === '000000') {
                    this.getAllList();
                    /*if (editingData.ackValue) {
                        this._ackVerifyHandle(this.selectItem);
                    }*/
                    this.message.create('success', `Update status successed!`);
                    this.isForceVisible = false;
                }
            });
        } else {
            editingData.ackValue = false;
            this.alarmService.ackTrafficAlert(editingData, header).subscribe((res: any) => {
                if (res.msg === '000000') {
                    this.getAllList();
                    this.ignoreAlert.emit('ignore');
                    // if (editingData.ackValue) {
                    //     this._ackVerifyHandle(this.selectItem);
                    // } else {
                    //     this.ignoreAlert.emit('ignore');
                    // }
                    // this.ignoreAlert.emit('ignore');
                    this.message.create('success', `Update status successed!`);
                    this.isForceVisible = false;
                }
            });
        }
    }

    changeItemStatus(flag) {
        if (this.editingItem === '') {
            this.message.create('warning', `Please select a alert!`);
            return;
        } else {
            if (!this.authService.isUserZoneChecked(this.selectItem.zoneID)) {
                return;
            }
            const zoneIds = this.ss.userZoneList.filter(z => !z.isTemp).map(z => z.id);
            const header = {
                zoneId: zoneIds.join(','),
                isFource: false
            };
            const editingData = {
                alertId: this.editingItem,
                ackValue: flag,
                userName: this.loginUserName, // 使用loginUserName,viet-316,
                zoneId: this.selectItem.zoneID
            };
            if (flag) {
                this.showItem = 'acknowledge';
            } else {
                this.showItem = 'Ignore';
            }
            this.translate.get('TrafficManagement.TrafficAlert.' + this.showItem).subscribe((res: string) => {
                this.showItem = res || '';
            });
            let contentLeft = 'Do you want to ';
            let contentRight = 'this record';
            let OK = 'OK';
            let Cancel = 'Cancel';
            this.translate.get('TrafficManagement.TrafficAlert.' + contentLeft).subscribe((res: string) => {
                contentLeft = res || '';
            });
            this.translate.get('TrafficManagement.TrafficAlert.' + contentRight).subscribe((res: string) => {
                contentRight = res || '';
            });
            this.translate.get('TrafficManagement.TrafficAlert.' + OK).subscribe((res: string) => {
                OK = res || '';
            });
            this.translate.get('TrafficManagement.TrafficAlert.' + Cancel).subscribe((res: string) => {
                Cancel = res || '';
            });
            this.confirmModal = this.modal.confirm({
                nzTitle: this.showItem,
                nzContent: contentLeft + this.showItem + contentRight + '?',
                nzOkText: OK,
                nzOnOk: () =>
                    this.alarmService.ackTrafficAlert(editingData, header).subscribe(
                        (res: any) => {
                            if (res.msg === '000000') {
                                this.getAllList();
                                if (flag) {
                                    // this._ackVerifyHandle(this.selectItem);
                                } else {
                                    this.ignoreAlert.emit('ignore');
                                }
                                this.message.create('success', `Update status successed!`);
                            } else if (res.msg === 'No operation permissions') {
                                this.isForceVisible = true;
                            }
                        },
                        (error: any) => {
                            this.message.create('warning', `Update status failed!`);
                        }
                    ),
                nzCancelText: Cancel
            });
        }
    }

    // websocket获取数据
    getAlertBySocket(data) {
        this.listOfData.pop();
        this.listOfData = [data, ...this.listOfData];
        this.editingItem = this.listOfData[0].alertID;
        this.selectItem = this.listOfData[0];
    }

    private _ackVerifyHandle(data: any) {
        const zone = this.authService.isUserZoneChecked(data.zoneID);
        if (!zone) {
            return;
        }
        if (zone.isTemp) {
            this.modal.confirm({
                nzTitle: `The Alert is out of your assigned zone! Do you want to continue?`,
                nzOkText: 'OK',
                nzCancelText: 'Cancel',
                nzOnOk: () => {
                    this.router.navigate(['/ccm/traffic-management/incident-record']);
                    // 用BS发送创建的事件
                    const _bully: Bully = {
                        type: SYSTEM_EVENT.CREATE_EVENT,
                        data,
                        fromGis: false
                    };

                    // 延迟发送BS, 避免resetBS带来的副作用
                    setTimeout(() => {
                        this.bully.setBSubject(_bully);
                    }, 1000);
                }
            });
            return;
        }
        this.router.navigate(['/ccm/traffic-management/incident-record']);
        // 用BS发送创建的事件
        const bully: Bully = {
            type: SYSTEM_EVENT.CREATE_EVENT,
            data,
            fromGis: false
        };

        // 延迟发送BS, 避免resetBS带来的副作用
        setTimeout(() => {
            this.bully.setBSubject(bully);
        }, 1000);
    }

    filterSearch() {
        this.pagination.currentPage = 1;
        this.pagination.pageSize = 10;
        this.getAllList();
    }

    onChange(result: Date): void {
        this.queryStartTime = result[0]
            ? moment(result[0])
                  .startOf('day')
                  .valueOf()
            : null;
        this.queryEndTime = result[1]
            ? moment(result[1])
                  .endOf('day')
                  .valueOf()
            : null;
        this.getAllList();
    }

    onAckChange(result: Date): void {
        this.queryAckStartTime = new Date(moment(result[0]).format('YYYY-MM-DD 00:00:00')).getTime();
        this.queryAckEndTime = new Date(moment(result[1]).format('YYYY-MM-DD 23:59:59')).getTime();
        this.getAllList();
    }

    disabledDate = (current: Date): boolean => {
        // Can not select days before today and today
        return differenceInCalendarDays(current, new Date()) > 0;
    };
}
